import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Topic } from './entities/topic.entity';
import { Repository } from 'typeorm';

@Injectable()
export class QuestionsService {
  constructor(
    @InjectRepository(Topic)
    private topicRepository: Repository<Topic>,
  ) {}
  getQuestions(): Promise<Topic[]> {
    return this.topicRepository.find();
  }
  // 修改
  async updateQuestion(body: Topic) {
    // 根据ID及负载进行更新
    const { id, ...rest } = body;
    // 需要处理这里的JSON格式
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    rest.questions = JSON.stringify(JSON.parse(rest.questions));
    rest.tags = JSON.stringify(JSON.parse(rest.tags));
    return this.topicRepository.update(id, rest);
  }

  // 新增
  async addQuestion(body: Topic) {
    // 需要处理这里的JSON格式
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    body.questions = JSON.stringify(JSON.parse(body.questions));
    body.tags = JSON.stringify(JSON.parse(body.tags));
    return this.topicRepository.save(body);
  }

  // 删除
  async deleteQuestion(id: number) {
    return this.topicRepository.delete(id);
  }
}
